import React, { useState, useRef, useCallback, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import {
  Upload,
  CheckCircle,
  Loader2,
  Download,
  X,
  FileSpreadsheet,
  AlertCircle,
  AlertTriangle,
} from "lucide-react";
import { toast } from "@/components/ui/use-toast";
import { TowerAPI } from "@/api/Towers";

// 常量定义 - 集中管理可配置项
const FILE_TYPES = {
  ALLOWED_EXTENSIONS: [".xlsx", ".xls", ".csv"],
  MIME_TYPES: [
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel",
    "text/csv",
  ],
  TEMPLATE_NAME: "杆塔导入模板.xlsx",
};

export default function ExeUploadModal({
  isOpen,
  onClose,
  projectId,
  onImportSuccess,
  projects = [],
  existingTowers = [], // 新增：传入已存在的杆塔数据用于重复检测
}) {
  // 状态管理
  const [file, setFile] = useState(null);
  const [fileDataList, setFileDataList] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);
  const [processingError, setProcessingError] = useState(null);
  const [currentStep, setCurrentStep] = useState("idle");
  const [isDragActive, setIsDragActive] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [duplicateErrors, setDuplicateErrors] = useState([]); // 新增：重复错误列表
  const [validationErrors, setValidationErrors] = useState([]); // 新增：验证错误列表
  const inputRef = useRef(null);

  // 当fileDataList变化时，默认全选并检测重复
  useEffect(() => {
    if (fileDataList.length > 0) {
      const items = fileDataList.map((item, index) => index);
      setSelectedItems(items);
      // 检测重复和验证错误
      detectDuplicatesAndValidationErrors(fileDataList);
    } else {
      setSelectedItems([]);
      setDuplicateErrors([]);
      setValidationErrors([]);
    }
  }, [fileDataList, existingTowers]);

  // 检测重复杆塔编号和验证错误
  const detectDuplicatesAndValidationErrors = useCallback((dataList) => {
    const duplicates = [];
    const validations = [];
    const seenTowerNumbers = new Set();
    
    // 收集已存在杆塔的编号
    const existingTowerNumbers = new Set(
      existingTowers.map(tower => tower.towerNumber?.toString().trim().toLowerCase())
    );

    dataList.forEach((item, index) => {
      const towerNumber = item.towerNumber?.toString().trim().toLowerCase();
      
      // 检测重复（在导入数据中）
      if (towerNumber) {
        if (seenTowerNumbers.has(towerNumber)) {
          duplicates.push({
            index,
            towerNumber: item.towerNumber,
            type: "internal", // 内部重复
            message: `杆塔编号 "${item.towerNumber}" 在导入文件中重复`
          });
        } else {
          seenTowerNumbers.add(towerNumber);
        }
      }

      // 检测与现有数据的重复
      if (towerNumber && existingTowerNumbers.has(towerNumber)) {
        duplicates.push({
          index,
          towerNumber: item.towerNumber,
          type: "external", // 外部重复（与现有数据重复）
          message: `杆塔编号 "${item.towerNumber}" 在项目中已存在`
        });
      }

      // 数据验证
      const errors = validateTowerData(item, index);
      if (errors.length > 0) {
        validations.push(...errors);
      }
    });

    setDuplicateErrors(duplicates);
    setValidationErrors(validations);
  }, [existingTowers]);

  // 杆塔数据验证
  const validateTowerData = (tower, index) => {
    const errors = [];
    const towerNumber = tower.towerNumber?.toString().trim();

    // 必填字段验证
    if (!towerNumber) {
      errors.push({
        index,
        field: "towerNumber",
        message: "杆塔编号不能为空"
      });
    }

    // 数值字段验证
    if (tower.height !== undefined && tower.height !== null && tower.height !== "") {
      const height = parseFloat(tower.height);
      if (isNaN(height) || height <= 0) {
        errors.push({
          index,
          field: "height",
          message: "高度必须是大于0的数字"
        });
      }
    }

    if (tower.groundElevation !== undefined && tower.groundElevation !== null && tower.groundElevation !== "") {
      const elevation = parseFloat(tower.groundElevation);
      if (isNaN(elevation) || elevation < 0) {
        errors.push({
          index,
          field: "groundElevation",
          message: "呼称高必须是非负数字"
        });
      }
    }

    if (tower.spanToNextTower !== undefined && tower.spanToNextTower !== null && tower.spanToNextTower !== "") {
      const span = parseFloat(tower.spanToNextTower);
      if (isNaN(span) || span <= 0) {
        errors.push({
          index,
          field: "spanToNextTower",
          message: "到下一塔档距必须是大于0的数字"
        });
      }
    }

    // 坐标验证
    if (tower.latitude !== undefined && tower.latitude !== null && tower.latitude !== "") {
      const lat = parseFloat(tower.latitude);
      if (isNaN(lat) || lat < -90 || lat > 90) {
        errors.push({
          index,
          field: "latitude",
          message: "纬度必须在-90到90之间"
        });
      }
    }

    if (tower.longitude !== undefined && tower.longitude !== null && tower.longitude !== "") {
      const lng = parseFloat(tower.longitude);
      if (isNaN(lng) || lng < -180 || lng > 180) {
        errors.push({
          index,
          field: "longitude",
          message: "经度必须在-180到180之间"
        });
      }
    }

    return errors;
  };

  // 清理错误状态
  const clearError = useCallback(() => {
    setProcessingError(null);
    setDuplicateErrors([]);
    setValidationErrors([]);
  }, []);

  // 验证文件类型
  const isValidFile = useCallback((file) => {
    if (!file) return false;
    const fileName = file.name.toLowerCase();
    return FILE_TYPES.ALLOWED_EXTENSIONS.some((ext) => fileName.endsWith(ext));
  }, []);

  // 处理文件选择
  const handleFileSelect = useCallback(
    async (files) => {
      if (!files || files.length === 0) return;

      clearError();
      const selectedFile = files[0];

      if (!isValidFile(selectedFile)) {
        setProcessingError(
          `文件类型不支持。请上传 ${FILE_TYPES.ALLOWED_EXTENSIONS.join("、")} 表格文件。`
        );
        setFile(null);
        return;
      }

      try {
        setCurrentStep("uploading");
        const response = await TowerAPI.import(selectedFile);
        setFileDataList(response.data);
        setFile(selectedFile);

        toast({
          title: "文件已解析",
          description: `已解析文件: ${selectedFile.name}，共${response.data.length}条数据`,
        });

        setCurrentStep("idle");
      } catch (error) {
        console.error("文件处理失败:", error);
        setProcessingError(`文件处理失败: ${error.message || "未知错误"}`);
        setFile(null);
        setCurrentStep("idle");
      }
    },
    [file, isValidFile, clearError]
  );

  // 移除选中的文件
  const handleRemoveFile = useCallback(() => {
    setFile(null);
    setFileDataList([]);
    setSelectedItems([]);
    clearError();
    if (inputRef.current) {
      inputRef.current.value = "";
    }
    toast({
      title: "已移除文件",
      description: "可以重新选择文件",
    });
  }, [clearError]);

  // 处理全选/取消全选 - 排除有错误的行
  const handleSelectAll = useCallback(() => {
    const validIndices = fileDataList
      .map((_, index) => index)
      .filter(index => 
        !duplicateErrors.some(error => error.index === index) &&
        !validationErrors.some(error => error.index === index)
      );

    if (selectedItems.length === validIndices.length && validIndices.length > 0) {
      setSelectedItems([]);
    } else {
      setSelectedItems(validIndices);
    }
  }, [selectedItems.length, fileDataList, duplicateErrors, validationErrors]);

  // 处理单个项选择
  const handleSelectItem = useCallback((index) => {
    // 检查是否有错误，有错误的项不能被选择
    const hasError = duplicateErrors.some(error => error.index === index) || 
                    validationErrors.some(error => error.index === index);
    
    if (hasError) {
      toast({
        title: "无法选择",
        description: "存在错误的行无法被选择",
        variant: "destructive"
      });
      return;
    }

    setSelectedItems((prev) =>
      prev.includes(index) ? prev.filter((itemIndex) => itemIndex !== index) : [...prev, index]
    );
  }, [duplicateErrors, validationErrors]);

  // 检查行是否有错误
  const hasRowError = useCallback((index) => {
    return duplicateErrors.some(error => error.index === index) || 
           validationErrors.some(error => error.index === index);
  }, [duplicateErrors, validationErrors]);

  // 获取行的错误信息
  const getRowErrors = useCallback((index) => {
    const dupErrors = duplicateErrors.filter(error => error.index === index);
    const valErrors = validationErrors.filter(error => error.index === index);
    return [...dupErrors, ...valErrors];
  }, [duplicateErrors, validationErrors]);

  // 拖拽事件处理
  const handleDrag = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  const handleDragIn = useCallback(
    (e) => {
      handleDrag(e);
      if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
        if (e.dataTransfer.items.length > 1) {
          setProcessingError("只能上传一个文件，请选择单个文件");
        } else {
          clearError();
        }
        setIsDragActive(true);
      }
    },
    [handleDrag, clearError]
  );

  const handleDragOut = useCallback(
    (e) => {
      handleDrag(e);
      setIsDragActive(false);
    },
    [handleDrag]
  );

  const handleDrop = useCallback(
    (e) => {
      handleDrag(e);
      setIsDragActive(false);

      if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
        if (e.dataTransfer.files.length > 1) {
          setProcessingError("只能上传一个文件，请选择单个文件");
          toast({
            title: "文件数量超限",
            description: "每次只能上传一个文件",
            variant: "destructive",
          });
          return;
        }
        handleFileSelect(e.dataTransfer.files);
        e.dataTransfer.clearData();
      }
    },
    [handleDrag, handleFileSelect]
  );

  // 输入框文件变更处理
  const handleInputChange = useCallback(
    (e) => {
      e.preventDefault();
      if (e.target.files && e.target.files.length > 0) {
        if (e.target.files.length > 1) {
          setProcessingError("只能上传一个文件，请选择单个文件");
          toast({
            title: "文件数量超限",
            description: "每次只能上传一个文件",
            variant: "destructive",
          });
          if (inputRef.current) {
            inputRef.current.value = "";
          }
          return;
        }
        handleFileSelect(e.target.files);
      }
    },
    [handleFileSelect]
  );

  // 处理文件上传 - 增加重复检测
  const handleUpload = useCallback(async () => {
    if (selectedItems.length === 0 || !projectId) return;

    // 检查是否还有错误项被选中
    const hasErrorsInSelection = selectedItems.some(index => hasRowError(index));
    if (hasErrorsInSelection) {
      toast({
        title: "存在错误数据",
        description: "请先修正错误数据后再上传",
        variant: "destructive",
      });
      return;
    }

    // 获取选中的数据项
    const selectedData = selectedItems.map(index => fileDataList[index]);

    try {
      setCurrentStep("uploading");
      await TowerAPI.importData(projectId, selectedData);
      setCurrentStep("success");
      toast({
        title: "上传成功",
        description: `已成功导入 ${selectedData.length} 条数据`,
      });
      onImportSuccess && onImportSuccess();
    } catch (error) {
      console.error("文件上传失败:", error);
      
      // 处理重复杆塔编号的错误响应
      if (error.response?.data?.duplicateTowerNumbers) {
        const duplicates = error.response.data.duplicateTowerNumbers;
        setProcessingError(`上传失败：存在重复的杆塔编号：${duplicates.join('，')}`);
      } else {
        setProcessingError(`上传失败: ${error.message || "未知错误"}`);
      }
      
      setCurrentStep("idle");
    }
  }, [selectedItems, projectId, fileDataList, onImportSuccess, hasRowError]);

  // 下载模板文件
  const handleDownloadTemplate = useCallback(async () => {
    if (isDownloading) return;
    try {
      setIsDownloading(true);
      const response = await TowerAPI.importTemplate();
      const blob = new Blob([response], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = FILE_TYPES.TEMPLATE_NAME;
      document.body.appendChild(a);
      a.click();

      setTimeout(() => {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, 100);

      toast({
        title: "模板下载成功",
        description: FILE_TYPES.TEMPLATE_NAME,
      });
    } catch (error) {
      console.error("模板下载失败:", error);
      setProcessingError(`模板下载失败: ${error.message || "未知错误"}`);
    } finally {
      setIsDownloading(false);
    }
  }, [isDownloading]);

  // 重置状态并关闭弹窗
  const resetState = useCallback(() => {
    setFile(null);
    setFileDataList([]);
    setSelectedItems([]);
    setProcessingError(null);
    setDuplicateErrors([]);
    setValidationErrors([]);
    setCurrentStep("idle");
    setIsDragActive(false);
    if (inputRef.current) {
      inputRef.current.value = "";
    }
    onClose && onClose();
  }, [onClose]);

  // 渲染错误提示
  const renderErrorAlerts = () => {
    if (duplicateErrors.length === 0 && validationErrors.length === 0) {
      return null;
    }

    return (
      <div className="space-y-2">
        {duplicateErrors.length > 0 && (
          <Alert variant="destructive" className="border-orange-200 bg-orange-50">
            <AlertTriangle className="h-4 w-4 text-orange-600" />
            <AlertTitle className="text-orange-800">重复杆塔编号检测</AlertTitle>
            <AlertDescription className="text-orange-700">
              <ul className="list-disc list-inside space-y-1">
                {duplicateErrors.slice(0, 5).map((error, index) => (
                  <li key={index}>
                    第{error.index + 1}行: {error.message}
                    {error.type === "external" && " (与现有数据重复)"}
                  </li>
                ))}
                {duplicateErrors.length > 5 && (
                  <li>... 还有 {duplicateErrors.length - 5} 个重复项</li>
                )}
              </ul>
            </AlertDescription>
          </Alert>
        )}

        {validationErrors.length > 0 && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>数据验证错误</AlertTitle>
            <AlertDescription>
              <ul className="list-disc list-inside space-y-1">
                {validationErrors.slice(0, 5).map((error, index) => (
                  <li key={index}>
                    第{error.index + 1}行: {error.message}
                  </li>
                ))}
                {validationErrors.length > 5 && (
                  <li>... 还有 {validationErrors.length - 5} 个错误</li>
                )}
              </ul>
            </AlertDescription>
          </Alert>
        )}
      </div>
    );
  };

  // 渲染选中的文件信息
  const renderSelectedFile = () => {
    if (!file) return null;

    return (
      <div className="mt-2 flex items-center justify-between p-1 bg-gray-50 rounded-md">
        <div className="flex items-center">
          <FileSpreadsheet className="h-5 w-5 mr-2 text-primary" />
          <span className="text-sm truncate max-w-[200px]">{file.name}</span>
          <span className="ml-2 text-xs text-gray-500">
            {(file.size / 1024).toFixed(1)} KB
          </span>
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={handleRemoveFile}
          className="h-7 w-7 p-0 text-gray-500 hover:text-red-500"
          aria-label="移除文件"
        >
          <X className="h-4 w-4" />
        </Button>
      </div>
    );
  };

  // 渲染数据表格
  const renderDataTable = () => {
    if (fileDataList.length === 0) return null;

    return (
      <div className="border rounded-lg overflow-hidden mt-4">
        <div className="max-h-[300px] overflow-y-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[50px]">
                  <Checkbox
                    checked={
                      selectedItems.length > 0 && 
                      selectedItems.length === fileDataList.length - 
                        duplicateErrors.length - validationErrors.length
                    }
                    onCheckedChange={handleSelectAll}
                    aria-label="全选有效数据"
                  />
                </TableHead>
                <TableHead>状态</TableHead>
                <TableHead>杆塔编号</TableHead>
                <TableHead>杆塔类型</TableHead>
                <TableHead>高度(m)</TableHead>
                <TableHead>呼称高(m)</TableHead>
                <TableHead>到下一塔档距(m)</TableHead>
                <TableHead>纬度</TableHead>
                <TableHead>经度</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {fileDataList.map((item, index) => {
                const isSelected = selectedItems.includes(index);
                const hasError = hasRowError(index);
                const rowErrors = getRowErrors(index);

                return (
                  <TableRow
                    key={index}
                    className={`${isSelected ? "bg-primary/5" : ""} ${
                      hasError ? "bg-red-50 border-l-4 border-l-red-500" : ""
                    }`}
                  >
                    <TableCell>
                      <Checkbox
                        checked={isSelected}
                        onCheckedChange={() => handleSelectItem(index)}
                        disabled={hasError}
                        aria-label={`选择第${index + 1}行`}
                      />
                    </TableCell>
                    <TableCell>
                      {hasError ? (
                        <Badge variant="destructive" className="text-xs">
                          错误
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="text-xs text-green-600">
                          正常
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell className={hasError ? "text-red-600 font-medium" : ""}>
                      {item.towerNumber || "-"}
                      {hasError && (
                        <div className="text-xs text-red-500 mt-1">
                          {rowErrors.map((error, i) => (
                            <div key={i}>• {error.message}</div>
                          ))}
                        </div>
                      )}
                    </TableCell>
                    <TableCell>{item.type || "-"}</TableCell>
                    <TableCell>{item.height || "-"}</TableCell>
                    <TableCell>{item.groundElevation || "-"}</TableCell>
                    <TableCell>{item.spanToNextTower || "-"}</TableCell>
                    <TableCell>{item.latitude || "-"}</TableCell>
                    <TableCell>{item.longitude || "-"}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>

        {/* 选择统计 */}
        <div className="bg-gray-50 p-3 border-t text-sm text-gray-600 flex justify-between items-center">
          <div>
            已选择{" "}
            <span className="font-medium text-primary">
              {selectedItems.length}
            </span>{" "}
            条，共 {fileDataList.length} 条
          </div>
          {(duplicateErrors.length > 0 || validationErrors.length > 0) && (
            <div className="text-red-600">
              {duplicateErrors.length + validationErrors.length} 个错误
            </div>
          )}
        </div>
      </div>
    );
  };

  // 渲染不同步骤的内容
  const renderContent = () => {
    switch (currentStep) {
      case "idle":
        return (
          <div className="grid gap-4 py-2">
            <div
              onDragEnter={handleDragIn}
              onDragLeave={handleDragOut}
              onDragOver={handleDrag}
              onDrop={handleDrop}
              className={`border-2 border-dashed rounded-lg p-6 transition-all duration-200 ${
                isDragActive
                  ? "border-primary/50 bg-primary/5"
                  : file
                  ? "border-primary bg-primary/5"
                  : "border-gray-300 hover:border-primary/50"
              }`}
            >
              <Input
                ref={inputRef}
                id="file-upload"
                type="file"
                accept={FILE_TYPES.MIME_TYPES.join(",")}
                onChange={handleInputChange}
                className="hidden"
                multiple={false}
              />

              {file ? (
                renderSelectedFile()
              ) : (
                <label
                  htmlFor="file-upload"
                  className="cursor-pointer flex flex-col items-center justify-center w-full h-full text-center"
                >
                  <div className="flex flex-col items-center justify-center pt-5 pb-6">
                    <FileSpreadsheet className="h-10 w-10 mb-3 text-gray-400" />
                    <p className="mb-2 text-sm text-gray-600">
                      <span className="font-semibold">点击上传文件</span>{" "}
                      或拖放文件至此处
                    </p>
                    <p className="text-xs text-gray-500">
                      支持 {FILE_TYPES.ALLOWED_EXTENSIONS.join("、")} 格式
                    </p>
                  </div>
                </label>
              )}
            </div>

            {/* 错误提示 */}
            {renderErrorAlerts()}

            {/* 显示数据表格 */}
            {file && renderDataTable()}

            {processingError && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertTitle>操作出错</AlertTitle>
                <AlertDescription>{processingError}</AlertDescription>
              </Alert>
            )}
          </div>
        );

      case "success":
        return (
          <div className="py-8 text-center">
            <Alert className="mb-6">
              <CheckCircle className="h-4 w-4 text-green-500" />
              <AlertTitle>上传成功</AlertTitle>
              <AlertDescription>
                已成功导入 {selectedItems.length} 条数据。
              </AlertDescription>
            </Alert>
          </div>
        );

      case "uploading":
        return (
          <div className="py-12 text-center">
            <Loader2 className="h-8 w-8 mx-auto text-primary animate-spin mb-4" />
            <p className="font-medium text-gray-700">正在处理文件...</p>
            <p className="text-sm text-gray-500 mt-2">
              这可能需要一些时间，请耐心等待。
            </p>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={resetState}>
      <DialogContent className="sm:max-w-[900px]">
        <DialogHeader>
          <DialogTitle>上传表格文件</DialogTitle>
          <DialogDescription>
            请先下载模板，按照模板格式填写数据后，上传文件进行导入。
            {existingTowers.length > 0 && (
              <span className="text-orange-600 font-medium">
                当前项目已有 {existingTowers.length} 个杆塔，系统会自动检测重复编号。
              </span>
            )}
          </DialogDescription>
        </DialogHeader>
        <div>
          <Button
            variant="outline"
            onClick={handleDownloadTemplate}
            className="w-full mb-4"
          >
            <Download className="mr-2 h-4 w-4" />
            下载导入模板（Excel格式）
          </Button>
          {renderContent()}
        </div>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={resetState}
            disabled={currentStep === "uploading"}
          >
            取消
          </Button>

          {currentStep === "idle" && (
            <Button
              onClick={handleUpload}
              disabled={
                !file ||
                selectedItems.length === 0 ||
                currentStep === "uploading" ||
                (duplicateErrors.length + validationErrors.length) > 0
              }
            >
              <Upload className="mr-2 h-4 w-4" />
              开始上传
              {(duplicateErrors.length + validationErrors.length) > 0 && 
                ` (${selectedItems.length} 条有效数据)`
              }
            </Button>
          )}

          {currentStep === "success" && (
            <Button onClick={resetState}>完成</Button>
          )}

          {currentStep === "uploading" && (
            <Button disabled>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              正在处理...
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}